<?php

namespace App\Util;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

/**
 * Created by PhpStorm.
 * User: Huyang
 * Date: 2016/10/12
 * Time: 10:59
 */
class Fast
{

    /**
     * @param     $table, 表名称
     * @param     $zoneId, 推荐位ID
     * @param int $limit 查询数据的数量，如果是1则返回一个一维数组，否则返回二维数组
     * @param string $field 要返回的字段
     * @return array
     */
    public static function zone($table, $zoneId, $limit = 1, $field = 'id,title,cover,abstract,created_at') {
        $data = self::cacheList('SELECT * FROM `zone_lists` WHERE `obj` = "'.$table.'" AND `zone_id` = '.$zoneId.' ORDER BY `zone_sort` ASC LIMIT 0, '.$limit);
        if ($data) {
            $ids = Helper::returnArrayVal($data, 'obj_id');
            if (count($ids) && is_array($ids)) {
                $result = self::cacheList('SELECT '.$field.' FROM '.$table.' WHERE `id` IN ('.implode(',',$ids).') AND `state` = 1');
                if ($result) {
                    $result = Helper::arrayMapByKey($result, 'id');
                    $tmp = [];
                    foreach ($ids as $key => $val) {
                        $tmp[$val] = $result[$val];
                    }
                    if ($limit == 1) {
                        return current($tmp);
                    } else {
                        return $tmp;
                    }
                }
            }
        }
        return [];
    }

    /**
     * @param     $spaceId
     * @param int $limit
     * @return bool
     */
    public static function adv($spaceId, $limit = 1) {
        $adv = self::query('SELECT `picture`,`link`,`text`,`plate_id`,`plate_type` FROM `ads`  WHERE `space_id` = '.$spaceId.' AND `state` = 1 ORDER BY `sort` ASC LIMIT 0, '.$limit);
        if ($limit > 1) {
            return $adv;
        } else {
            return $adv[0];
        }
    }

    /**
     * @param     $typeId
     * @param int $limit
     * @param int $cover
     * @param int $zoneId
     * @param int $notId
     * @return false
     *
     */
    public static function article($typeId, $limit = 3, $cover = 0, $zoneId = 0, $notId = 0) {
        $sqlFilter = '';
        if (Helper::sqlId($notId)) {
            $sqlFilter .= ' AND `id` NOT IN ('.$notId.')';
        }
        if ($typeId) {
            $ids = self::childIds($typeId);
            $sqlFilter .= ' AND (`type_id` IN ('.substr($ids,0,-1).'))';
        }
        if (Helper::sqlId($zoneId)) {
            $sqlFilter .= ' AND `zone_id` % '.$zoneId;
        }
        if ($cover) {
            $sqlFilter .= ' AND `cover` != "" ';
        }
        $data = self::cacheList('SELECT id,type_id,title,zone_id,zone_sort,abstract,tag,click,coin,cover,video,jump,date FROM articles WHERE 1 '.$sqlFilter.' AND `state` = 1 ORDER BY `date` DESC ,`id` DESC LIMIT 0, '.$limit);
        if ($data) {
            if ($limit == 1) {
                return $data[0];
            } else {
                return $data;
            }
        } else {
            return false;
        }
    }

    /**
     * @param int $type
     * @return bool
     */
    public static function link($type = 0) {
        if ($type) {
            $filter = '`type_id` = '.$type;
        } else {
            $filter = '1';
        }
        return self::cacheList('SELECT * FROM links WHERE '.$filter.' ORDER BY `sort` ASC');
    }

    /**
     * 向下查询,获取某个ID下的所有子集ID
     * @param        $id
     * @param string $table
     * @param string $primary
     * @return string
     */
    public static function childIds($id, $table = 'types', $primary = 'id') {
        if ($id) {
            $ids = $id.',';
            $data = self::cacheList('SELECT `'.$primary.'` FROM '.$table.' WHERE 1 AND `parent_id` = '.$id);
            if (is_array($data)) {
                foreach ($data as $record) {
                    if ($record[$primary]) {
                        $ids .= self::childIds($record[$primary], $table, $primary);
                    }
                }
            }
            return $ids;
        }
    }

    /**
     * 向上查询法,列出自己的父类ID组合,结果用逗号分隔
     * @param $table
     * @param $primary
     * @param $parentId
     * @param $ids
     */
    public static function parent($table, $primary, $parentId, &$ids) {
        if ($parentId) {
            if (!$ids) {
                $ids = $parentId.',';
            }
            $data = self::cacheRow('SELECT `'.$primary.'`,`parent_id` FROM ' . $table . ' WHERE `'.$primary.'` = '.$parentId);
            if ($data[$primary]) {
                $ids .= $data['parent_id'].',';
                self::parent($table, $primary, $data['parent_id'], $ids);
            }
        }
    }

    /**
     * 获取新闻分类
     * @return array
     */
    public static function types() {

        $data = self::cacheList('SELECT * FROM `types` WHERE 1 ORDER BY `sort` ASC, `id` ASC');

        $output = Array();

        self::gradation('id', $data, $output);

        return $output;

    }

    /**
     * 获取分类
     * @param     $sql
     * @param     $primary
     * @param int $parentId
     * @return mixed
     */
    public static function type($sql, $primary, $parentId = 0) {

        $result = self::cacheList($sql);

        self::gradation($primary, $result, $data, intval($parentId));

        return $data;

    }

    /**
     * 重新排列
     * @param       $primary
     * @param       $arr
     * @param array $arr2
     * @param int   $perId
     * @param int   $lv
     */
    public static function gradation($primary, $arr, &$arr2 = Array(), $perId = 0, $lv=0) {

        if ((bool)$arr) {
            foreach ($arr as $value) {
                if ($value['parent_id'] == $perId) {
                    $value['lv'] = $lv;
                    $arr2[$value[$primary]] = $value;
                    $lv++;
                    self::gradation($primary, $arr, $arr2, $value[$primary], $lv--);
                }
            }
        }

    }

    /**
     * 将无限分类重新整理成一个带层级的数组
     * @param       $primary ,因为此方法用于多个对象,所以需将表内的主键传入进来, 如 m_id, o_id, d_id等
     * @param       $input ,需要进行重构的数据
     * @param array $output 重构后保存至该数组内
     * @param int   $perId 父ID
     */
    public static function refactor($primary, $input, &$output = Array(), $perId = 0) {

        if ((bool)$input) {
            $check = False;
            foreach ($input as $key => $val) {
                if ($val['parent_id'] == $perId) {
                    $check = True;
                    $output[$val[$primary]] = $val;
                    self::refactor($primary, $input, $output[$val[$primary]]['children'], $val[$primary]);
                }
            }
            if (!$check) {
                $output = null; //this node have not child
            }
        }
    }

    /**
     * @param $sql
     * @param string $key 自定义key
     * @return bool
     */
    public static function cacheList($sql, $key = '') {
        return self::query($sql, $key);
    }

    /**
     * @param        $sql
     * @param string $key 自定义key
     * @return bool
     */
    public static function cacheRow($sql, $key = '') {
        if ($data = self::query($sql, $key)) {
            return $data[0];
        }
        return False;
    }

    /**
     * @param $sql
     * @param string $key
     * @return bool
     */
    public static function query($sql, $key = '') {
        if (empty($key)) {
            $key = 'SQL:'.md5($sql);
        }
        $data = Cache::remember($key, Config::get('cache.expire'), function() use($sql) {
            return DB::select($sql);
        });
        if ($data) {
            $data = array_map(function ($value) {
                return (array)$value;
            }, $data);
            return $data;
        }
        return false;
    }


}